<?php
namespace cms\modules\v1\models\circle;

use common\models\Functions;
use common\models\message\MessageText;
use common\models\Status;
use common\models\yiGoods\YiGoodsBusiness;
use yii\base\Exception;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class Circle extends \common\models\circle\Circle
{

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {
            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'id DESC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);
            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     */
    public function getSearch () {
        $where['is_delete'] = Status::COMMON_RADIO_NO;
        $andWhere = [];
        $status = Yii::$app->request->get('status','');
        $is_see = Yii::$app->request->get('is_see','');
        $loginName = Yii::$app->request->get('login_name','');
        if ($status) {
            $where['status'] = (int) $status;
        }
        if ($is_see) {
            $where['is_see'] = (int) $is_see;
        }

        if ($loginName) {
            $ids = \common\models\user\User::searchByName($loginName);
            $where['user_id'] = $ids;
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with([
            'user' => function ($q) {
                $q -> select(['id','nick_name','user_face','login_name']);
            },

        ])->asArray()->all();

        foreach ($list as &$v) {
            $singImUserInfo = ArrayHelper::getValue($v,'user',[]);
            $singUserInfo = ArrayHelper::getValue($singImUserInfo,'user',[]);
            $singleLevelInfo = ArrayHelper::getValue($singImUserInfo,'userLevel',[]);

            $imageTmp = null;
            $videoTmp = null;
            $imageArray = $v['images'] ? json_decode($v['images'],true) : [];
            if ($imageArray) {
                foreach ($imageArray as $vv) {
                    $over = substr($vv,-3);
                    if($over == 'jpg' || $over == 'png' || $over == 'jpeg' ){
                        $imageTmp[] = static::getImages($vv);
                    }
                    if($over == 'mp4' || $over == 'wmv' || $over == 'avi' ){
                        $videoTmp = static::getImages($vv);
                    }
                }
            }

            $v['user_face'] = static::getAvatar($singImUserInfo['user_face']);
            $v['nick_name'] = $singImUserInfo['nicheng'] ?: '';
            $v['phone'] = $singUserInfo['login_name'] ?: '';
            $v['level'] = $singleLevelInfo['name'] ?: 'L0';
            $v['time'] = $v['update_time'] ?: $v['create_time'];
            $v['deputy'] = $imageTmp;
            $v['video'] = $videoTmp;
        }
        return $list;
    }

    /**
     * 获取修改信息
     * @param int $id
     * @return array
     */
    public function getInfo($id = 0) {
        try {
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            $where['id'] = $id;
            $info = static::getObjectByWhere($where)->with([
            ])->asArray()->one();
            if (empty($info)) {
                throw new Exception('未知信息');
            }
            $info['image'] = [
                'url' => $info['image'] ? $this->getImages($info['image']) : '',
                'path' => $info['image']  ?: '',
            ];

            $info['yx_num'] = floatval($info['yx_num']);
            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 添加修改
     * @return array
     */
    public function addEdit() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $id = Yii::$app->request->post('id',0);
            $post = Yii::$app->request->post();
            $data = [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));

            if (!empty($id)) {
                //更新操作
                $data['update_time'] = date('Y-m-d H:i:s');

                $res = static::updateData($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception('更新失败');
                }

            } else {
                //添加操作
                $data['create_time'] = $data['update_time'] = date('Y-m-d H:i:s');

                $res = static::insertData($data);
                if ($res === false) {
                    throw new Exception('添加失败');
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    //删除
    public function getDelete()
    {
        try{
            $get = Yii::$app->request->get();
            $id = (int) $get['id'];
            if (empty($id)) {
                throw new Exception("参数有误");
            }
            $update['is_delete'] = status::COMMON_STATUS_SHOW;
            $res = static::updateData($update,['id' => $id]);
            if (!$res){
                throw new Exception('删除失败');
            }
            return Functions::formatRestAPI(0, '删除成功');
        }catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    public function getMapForSelect() {
        $list = static::getByWhere();
        $result = [];
        foreach ($list as $v) {
            $result[] = [
                "id" => $v['id'],
                'name' => $v['name']
            ];
        }
        return Functions::formatRestAPI(0, '', $result);
    }

    /**
     * 审核
     * @return array
     * @throws \yii\db\Exception
     */
    public function saveExamine() {
        $trans = Yii::$app->db->beginTransaction();
        try{
            $id = Yii::$app->request->post('id','');
            $status = Yii::$app->request->post('status','');
            $reason = Yii::$app->request->post('reason','');
            if (empty($id)|| empty($status)){
                throw new Exception('缺少参数');
            }

            if (!is_array($id)) {
                $ids = [$id];
            } else {
                $ids = $id;
            }

            if($status == Status::COMMON_CHECKING_DEFEAT) {
                if (empty($reason)){
                    throw new Exception('请填写驳回理由');
                }
                $data['reason'] = $reason;
            }

            foreach ($ids as $v) {
                $data['status'] = $status;
                $res = static::updateData($data, ['id' => $v]);
                if ($res === false){
                    throw new Exception('操作失败');
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    public function queryAudit() {
        $where['status'] = Status::COMMON_CHECKING_WAITING;
        $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;

        $count = static::getCountByWhere($where);

        return Functions::formatRestAPI(0, '', $count);
    }


}
